package org.zht.dormpro.auth.controller;

import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.zht.dormpro.auth.bean.PageBean;
import org.zht.dormpro.pub.constant.Enums;
import org.zht.dormpro.auth.model.SysDept;
import org.zht.dormpro.auth.model.SysRole;
import org.zht.dormpro.auth.model.SysUser;
import org.zht.dormpro.auth.model.SysUserRole;
import org.zht.dormpro.auth.service.IDeptService;
import org.zht.dormpro.auth.service.IRoleService;
import org.zht.dormpro.auth.service.ISysUserService;
import org.zht.dormpro.pub.ResponseMap;

import java.util.*;

@Controller
@RequestMapping("/auth/user")
public class UserController {
    private static final Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private ISysUserService  sysUserService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IDeptService deptService;

    @RequestMapping("/listUser")
    @RequiresPermissions("user:list:all")
    @ResponseBody
    public ResponseMap listUser(@RequestParam Map<String,Object> params){
        PageBean pageBean = new PageBean(params);
        List<SysUser> list = sysUserService.getUserByCondition(pageBean);
        Map<String,Object> attr=new HashMap<>();
        attr.put("total",pageBean.getTotal());
        return ResponseMap.success(list,attr);
    }
    @RequestMapping("/addUser")
    @ResponseBody
    public ResponseMap addUser(SysUser sysUser, String roleIds){
        Integer id = sysUserService.addUser(sysUser);
        if(id>0){
            //添加用户角色关系
            String[] split = roleIds.split(",");
            boolean success = sysUserService.addRoleUserRL(new ArrayList<>(Arrays.asList(split)),id);
            if(success) {
                return ResponseMap.success("用户添加成功!");
            }
        }else {
            return ResponseMap.error("用户添加失败!");
        }
        return ResponseMap.error("用户添加失败!");
    }

    @RequestMapping("/userPage")
    public String userPage(){
        return "/user/user_list";
    }
    @RequestMapping("/userAddPage")
    public String userAddPage(Model model){
        //获取所有角色信息
        List<SysRole> roles = roleService.getAllRole(0);
        model.addAttribute("roles",roles);
        return "/user/user_add";
    }
    @ResponseBody
    @RequestMapping("/checkUserCode")
    public boolean userCodeExit(String usercode){
        //根据userCode找用户
        SysUser sysUserByUsercode = sysUserService.getSysUserByUsercode(usercode);
        return sysUserByUsercode==null;
    }
    @RequestMapping(value = "/deleteUser",method = RequestMethod.POST)
    @ResponseBody
    public ResponseMap deleteUser(Integer id){
        boolean success = sysUserService.deleteUser(id);
        if(success){
            //删除用户角色
            boolean b = sysUserService.deleteUserRoRL(id, Enums.URStatus.USER);
            if(b){
                return ResponseMap.success("用户删除成功!");
            }
        }
        return ResponseMap.error("用户删除失败!");
    }
    @RequestMapping(value = "/batchDeleteUser",method = RequestMethod.POST)
    @ResponseBody
    public ResponseMap batchDeleteUser(@RequestParam("userIds[]") String[] userIds){
        if(userIds!=null&& userIds.length>0) {
            for (String userId : userIds) {
                boolean success = sysUserService.deleteUser(Integer.valueOf(userId));
                if (success) {
                    //删除用户角色
                    boolean b = sysUserService.deleteUserRoRL(Integer.valueOf(userId), Enums.URStatus.USER);
                }
            }
           return ResponseMap.success("用户删除成功!");
        }
        return ResponseMap.error("用户删除失败!");
    }
    @RequestMapping("/editUserPage/{id}")
    public String editUserPage(Model model,@PathVariable("id") Integer id){
        //查询用户信息
        SysUser sysUser = sysUserService.getSysUserById(id);
        model.addAttribute("user",sysUser);
        //查询所属部门
        if(sysUser!=null) {
            SysDept dept = deptService.getDeptById(sysUser.getDeptId());
            model.addAttribute("deptName", dept!=null?dept.getName():"");
        }
        //查询所有角色
        List<SysRole> allRole = roleService.getAllRole(0);
        //查询用户拥有的角色
        List<SysUserRole> userRoRL = sysUserService.getUserRoRL(id, Enums.URStatus.USER);
        List<Integer> temp = null;
        if(CollectionUtil.isNotEmpty(userRoRL)){
            temp = new ArrayList<>();
            for (SysUserRole sysUserRole : userRoRL) {
                temp.add(sysUserRole.getSysRoleId());
            }
        }
        if(CollectionUtil.isNotEmpty(allRole)){
            for (SysRole sysRole : allRole) {
                if(CollectionUtil.isNotEmpty(temp)) {
                    sysRole.setChecked(temp.contains(sysRole.getId())
                            ? true : false);
                }
            }
        }
        model.addAttribute("roles",allRole);
        return "/user/user_edit";
    }

    @ResponseBody
    @RequestMapping("/editUser")
    public ResponseMap editUser(SysUser sysUser, String roleIds){
        //更新用户
        boolean success = sysUserService.update(sysUser);
        if(success){
            //添加用户角色关系
            String[] split = roleIds.split(",");
            boolean b = sysUserService.updateUserRoleRL(new ArrayList<>(Arrays.asList(split)),sysUser.getId());
            if(b) {
                return ResponseMap.success("用户更新成功!");
            }
        }else {
            return ResponseMap.error("用户更新失败!");
        }
        return ResponseMap.error("用户更新失败!");
    }
    @ResponseBody
    @RequestMapping("/resetPassword")
    public ResponseMap resetPassword(Integer id,String password){
        boolean success = sysUserService.resetPassword(id,password);
        return ResponseMap.success("密码修改成功");
    }


}
